package io.lvdaxian.mybatis07.datasource.unpooled;


import io.lvdaxian.mybatis07.datasource.DataSourceFactory;
import io.lvdaxian.mybatis07.reflection.MetaObject;
import io.lvdaxian.mybatis07.reflection.SystemMetaObject;

import javax.sql.DataSource;
import java.util.Properties;

public class UnpooledDataSourceFactory implements DataSourceFactory {
  protected DataSource dataSource;
  
  public UnpooledDataSourceFactory() {
    this.dataSource = new UnpooledDataSource();
  }
  
  @Override
  public DataSource getDataSource() {
    return dataSource;
  }
  
  @Override
  public void setProperties(Properties props) {
    MetaObject metaObject = SystemMetaObject.forObject(dataSource);
    
    for (Object key : props.keySet()) {
      // 这里拿到每个key name
      String propertyName = (String) key;
      // 判断是否有setter 方法
      if (metaObject.hasSetter(propertyName)) {
        // 拿到对应的值
        String value = (String) props.get(propertyName);
        // 这里进行类型转换
        Object convertedValue = convertValue(metaObject, propertyName, value);
        metaObject.setValue(propertyName, convertedValue);
      }
    }
  }
  
  /**
   * 根据setter的类型,将配置文件中的值强转成相应的类型
   */
  private Object convertValue(MetaObject metaObject, String propertyName, String value) {
    Object convertedValue = value;
    Class<?> targetType = metaObject.getSetterType(propertyName);
    if (targetType == Integer.class || targetType == int.class) {
      convertedValue = Integer.valueOf(value);
    } else if (targetType == Long.class || targetType == long.class) {
      convertedValue = Long.valueOf(value);
    } else if (targetType == Boolean.class || targetType == boolean.class) {
      convertedValue = Boolean.valueOf(value);
    }
    return convertedValue;
  }
}
